package com.xw.hchat.service.impl;

import com.xw.hchat.mapper.TbFriendMapper;
import com.xw.hchat.mapper.TbFriendReqMapper;
import com.xw.hchat.mapper.TbUserMapper;
import com.xw.hchat.pojo.*;
import com.xw.hchat.pojo.vo.User;
import com.xw.hchat.service.UserService;
import com.xw.hchat.util.FastDFSClient;
import com.xw.hchat.util.IdWorker;
import com.xw.hchat.util.QRCodeUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;

/**
 * @ClassName UserServiceImpl
 * @Author liu zhiyong
 * @Date 2020/8/17 17:56
 * @Version 1.0
 */
@Service
@Transactional
public class UserServiceImpl implements UserService {

    @Resource
    private TbUserMapper userMapper;
    @Autowired
    private IdWorker idWorker;
    @Autowired
    private FastDFSClient fastDFSClient;
    @Autowired
    private Environment environment;
    @Autowired
    private QRCodeUtils qrCodeUtils;
    @Resource
    private TbFriendMapper friendMapper;
    @Resource
    private TbFriendReqMapper friendReqMapper;

    @Override
    public List<TbUser> findAll() {
        return userMapper.selectByExample(null);
    }

    @Override
    public User login(String username, String password) {
        if(StringUtils.isNotBlank(username) && StringUtils.isNotBlank(password)){

            TbUserExample example = new TbUserExample();
            TbUserExample.Criteria criteria = example.createCriteria();
            criteria.andUsernameEqualTo(username);
            List<TbUser> userList = userMapper.selectByExample(example);
            if(userList!=null && userList.size()==1){
                //对密码进行校验
                //先将前端提交的明文加密再进行比较
                String encodingPassword = DigestUtils.md5DigestAsHex(password.getBytes());
                if(encodingPassword.equals(userList.get(0).getPassword())){
                    User user = new User();
                    BeanUtils.copyProperties(userList.get(0), user);
                    return user;
                }
            }
        }
        return null;
    }

    @Override
    public void register(TbUser user) {
        try {
            //1.判断用户名是否存在
            TbUserExample example = new TbUserExample();
            TbUserExample.Criteria criteria = example.createCriteria();
            criteria.andUsernameEqualTo(user.getUsername());
            List<TbUser> userList = userMapper.selectByExample(example);
            if(userList!=null && userList.size()>0){
                throw new RuntimeException("用户名已经存在");
            }
            //2.将用户信息注册到数据中
            //使用雪花算法来生成唯一id
            user.setId(idWorker.nextId());
            //对前端传递的明文密码加密后存储
            user.setPassword(DigestUtils.md5DigestAsHex(user.getPassword().getBytes()));
            user.setPicSmall("");
            user.setPicNormal("");
            user.setNickname(user.getUsername());
            user.setSign("");
            user.setCreatetime(new Date());

            /*
            生成二维码，并且将二维码的路径保存到数据库中
             */
            //要生成的二维码中的字符串内容
            String qrCodeStr = "hchat://" + user.getUsername();
            //获取一个临时目录，用来保存临时的二维码图片
            String tempDir = environment.getProperty("hcat.tmpdir");
            String quCodeFilePath_temp = tempDir + user.getUsername() + ".png";
            qrCodeUtils.createQRCode(quCodeFilePath_temp, qrCodeStr);

            //将临时目录中保存的二维码图片上传到fastDFS中
            String qrCodeUrl = environment.getProperty("fdfs.httpurl") + fastDFSClient.uploadFile(new File(quCodeFilePath_temp));
            user.setQrcode(qrCodeUrl);

            userMapper.insert(user);
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("注册失败");
        }

    }

    @Override
    public User upload(MultipartFile file, String userid) {

        try {
            //返回在fastDFS中的url路径，这个路径
            String url = fastDFSClient.uploadFile(file);

            //在fastDFS上传的时候，会自动生成一个缩略图
            //文件名_150x150.后缀
            String[] split = url.split("\\.");
            String fileName = split[0];
            String ext = split[1];
            //缩略图路径
            String picSmallUrl = fileName + "_150x150." + ext;

            TbUser tbUser = userMapper.selectByPrimaryKey(userid);
            String prefix = environment.getProperty("fdfs.httpurl");
            tbUser.setPicNormal(prefix + url);//设置大图
            tbUser.setPicSmall(prefix + picSmallUrl);//设置缩略图

            userMapper.updateByPrimaryKey(tbUser);//更新到数据库中

            //将用户信息返回到controller
            User user = new User();
            BeanUtils.copyProperties(tbUser, user);
            return user;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public void updateNickname(String id, String nickname) {
        if(StringUtils.isNotBlank(nickname)){
            TbUser tbUser = userMapper.selectByPrimaryKey(id);
            tbUser.setNickname(nickname);

            userMapper.updateByPrimaryKey(tbUser);
        }else {
            throw new RuntimeException("昵称不能为空");
        }
    }

    @Override
    public User findById(String userid) {
        TbUser tbUser = userMapper.selectByPrimaryKey(userid);
        User user = new User();
        BeanUtils.copyProperties(tbUser, user);

        return user;
    }

    @Override
    public User findByUsername(String userid, String friendUsername) {
        if(StringUtils.isNotBlank(friendUsername)){

            TbUserExample example = new TbUserExample();
            TbUserExample.Criteria criteria = example.createCriteria();
            criteria.andUsernameEqualTo(friendUsername);
            List<TbUser> userList = userMapper.selectByExample(example);
            TbUser friend = userList.get(0);

            User friendUser = new User();
            BeanUtils.copyProperties(friend, friendUser);

            return friendUser;
        }else{
            throw new RuntimeException("昵称不能为空");
        }
    }
}
